package com.qfedu.openplateform.manager.controller;


import com.qfedu.openplateform.manager.entity.AdminUser;
import com.qfedu.openplateform.manager.entity.AjaxMessage;
import com.qfedu.openplateform.manager.entity.Menu;
import com.qfedu.openplateform.manager.service.AdminUserService;
import com.qfedu.openplateform.manager.service.MenuService;
import com.qfedu.openplateform.manager.util.AdminConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class SystemController {
    @Autowired
    private MenuService menuService;
    @Autowired
    private AdminUserService adminUserService;


    /**
     * 退出登录
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "login.html";
    }

    /**
     * 登录
     * @param email
     * @param password
     * @param session
     * @return
     */
    @RequestMapping("/dologin")
    @ResponseBody
    public AjaxMessage login(String email, String password, HttpSession session) {
        AdminUser user = adminUserService.doLogin(email, password);
        if (user == null) {
            return new AjaxMessage(false);
        }
        session.setAttribute(AdminConstants.SESSION_USER, user);

        List<Menu> menuList = menuService.getUserMenuList(user.getId());

        session.setAttribute(AdminConstants.USER_MENU,menuList);
        return new AjaxMessage(true);
    }

    /**
     * 错误处理
     * @return
     */
    @RequestMapping("/auth_error")
    public String error() {
        return "error.html";
    }

    /**
     * 获取首页侧边栏
     * @param session
     * @param response
     * @return
     */
    @RequestMapping("/side")
    @ResponseBody
    public AjaxMessage getMenuTree(HttpSession session, HttpServletResponse response) {
        AdminUser user = (AdminUser) session.getAttribute(AdminConstants.SESSION_USER);
        if (user == null) {
            try {
                response.sendRedirect("/login.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new AjaxMessage(true, null, new ArrayList<>());
        }
        List<Menu> menus = menuService.getUserPermission(user.getId());
        return new AjaxMessage(true, null, menus);
    }
}
